<?php

namespace app\api\controller;

use app\admin\model\Member;
use app\api\model\Api;
use think\Db;
use think\model\Pivot;
use think\Request;
use think\Validate;
use function GuzzleHttp\Psr7\parse_query;

class TaskController extends AppController
{
    private $key = '35a9076b540527e77691521fea7e5ef8';
    private $price = [];
    private $username = 'u_1740222';
    private $address = 'http://api.lieliu.com:1024';
    private $version = '5';
    public function initialize()
    {
        parent::initialize();
    }
    public function add(){
        if (!isset($this->param['sign'])) {
            $this->encode_json('5000', '没有检测到签名');
        }
        $sign = $this->param['sign'];
        $Api = Api::with(['ApiPrice' => function ($query) {
            $query->field('level_id,price,api_id');
        }, 'ApiFieldParam'])->where('sign', $sign)->find();
        if ($Api) {
            $Api = $Api->toArray();
        } else {
            $this->encode_json('404', '访问错误');
        }
        $level = [];
        foreach ($Api['api_price'] as $item) {
            $level[$item['level_id']]= $item;
        }
        /****************获取参数************/

        array_walk($Api, function (&$value, &$key) use (&$param) {
            if ($key == 'api_field_param') {
                foreach ($value as $key => &$item) {
                    $name = $item['pivot']['name'] ? $item['pivot']['name'] : $item['field_name'];
                    $param['field_name'][$name] = $item['pivot']['default'];
                    if ($item['is_param']) {
                        $param['field'][] = $item['pivot']['name'];
                    }
                    if ($item['pivot']['is_require']) {
                        $param['require'][$name] = $item['field_alias'];
                    }
                    $param['param'][$name] = $item['field_name'];
                    if (!empty($item['pivot']['price'])){
                        $param['price'][$item['field_name']] =isJson($item['pivot']['price'],true) ? isJson($item['pivot']['price'],true) :$item['pivot']['price'];
                    }
                }
            }
        });
        $level_id = $this->userInfo->level_id;  /*获取用户等级*/
        $price =   isset( $level[$level_id])?   $level[$level_id]['price']  :  $Api['price'];
        $client_field = $this->request->only($param['field']);
        foreach ($client_field as $key => $item) {
            if (isset($param['require'][$key]) && empty($item)) {
                $this->encode_json('40004', $param['require'][$key] . '必填不能为空');
            }
        }
        $submit_field = array_merge($param['field_name'], array_filter($client_field));
        $field = [];
        foreach ($param['param'] as $key => $item) {
            $field[$item] = $submit_field[$key];
        }
        $attr_price = [];
        $field['count'] = (int)$field['send_day']*(int) $field['count']; // 总发布量
        foreach ($field as $key=>$item) {
            if (isset($param['price'][$key])){
                if (is_array($param['price'][$key])){
                   if ( isset($param['price'][$key][$item])){

                        $attr_price[$key] = (int)$param['price'][$key][$item]*$field['count'];
                   }else{
                       $this->encode_json('40004', $key.'格式错误可选值有'.join(',',array_keys($param['price'][$key])));
                   }
                }else{
                    $attr_price[$key] = $item*$param['price'][$key];
                }
            }
        }
        $attrPrice =array_sum($attr_price);
        Db::startTrans();
        $member   =Member::where('member_id',$this->userInfo->user_id)->find();
        $price =$price*$field['count']+$attrPrice;
         if (((int)$member->currency)<($price)){
            $this->encode_json('40004','余额不足');
        }
        $toll = $member->setDec('currency',$price);
        if (!$toll){
            $this->encode_json('40004','扣费失败');
        }
        $status_code = config('api.status');
        $params =_create_sign($Api['api_path'],$field);
        $send_result= curl_request(config('lieliu.url'). $Api['api_path'], 'post', $params);
        if (!isset($send_result['data'])){

            $this->encode_json('4000','错误');
        }
        if (($send_result['data']['status']<0)){
            $this->encode_json($send_result['data']['status'], $send_result['data']['tips']);
            Db::rollback();
        } else {
            Db::commit();
            $task['order_id']= $send_result['order_id']; // 订单号
            $task['order_price']= $price*$field['count'];  // 订单价格
            $task['task_name']= $Api['api_name']; // 任务类型
            $task['api_id']=$Api['api_id']; // 接口id
            $task['order_status'] =0; // 1 发布成功  2 待处理  3部分成功  4等待退款  5 取消中
            $task['count']  = $field['count']; // 发布量
            $task['show'] = isset($field['show']) ? $field['send_day']*$field['show']  : 0 ; // 展现量
            $task['complete_show'] = isset($field['show']) ? $field['send_day']*$field['show']  : 0 ; // 展现量
            $task['send_day'] = $field['send_day']; // 发布天数
            $task['keyword'] = isset($field['keyword']) ?  $field['keyword'] : '' ; // 关键字
            $task['remark'] = isset($field['remark']) ? $field['remark'] : '';
            $task['member_id'] = $this->userInfo->user_id;
            $task['send_time'] =time();
            $task['taobao_token'] = isset($field['taobao_token']) ? $field['taobao_token'] : '';
            $task['begin_time'] = isset($field['begin_time']) ? strtotime($field['begin_time']) : '';
            Db::name('task_record')->insert($task);
            $this->encode_json(200,$send_result['data']['tips'], ['order_id' =>$send_result['order_id'],'price'=> $price,'over'=>$member['currency']]);
        }
    }
    public function read(Request $request){
       $param =  $request->only([
           'id',
           'page',
           'limit',
           'where',
        ]);

       $record  = Db::name('task_record')->where('member_id',$this->userInfo->user_id);
       if (isset($param['id'] ) && !empty($param['id'])){
           $record->where('order_id','in',$param['id']);
       }
        if (!empty(($param['where']))){

        }
        if (isset($param['status'] ) && !empty($param['status'])){
            $record->where('order_id',$param['status']);
        }
       $count = $record->count();
       if (isset($param['page'])&& !empty($param['page'])){
           $record->page($param['page'],$param['limit']);
       }
       $list  = $record->order('task_record_id','desc')->select();
       $this->encode_json(200,'返回成功',['count'=>$count,'list'=>$list]);
    }
    // 取消任务
    public function cancel(Request $request){
        $param =  $request->only(['id']);
        $params =_create_sign('/ll/task_cancel',$param);
        $result =curl_request($this->address.'/ll/task_cancel','post',$params);
        $task= Db::name('task_record')
                ->where('order_id','in',$param['id'])
                ->setField('order_status',8);

        if ($result['data']['status'] == '-9'){
            $this->encode_json('4004',$result['data']['tips']);
        }else{
            $this->encode_json(200,'取消成功');
        }
    }
    public function get_goods_info(Request $request){
        $url = $request->param('url');
        $query = parse_query($url);
        $parser_url = parse_url($url);
        if (isset($parser_url['scheme']) && isset($parser_url['host'])){
            $u = $parser_url['scheme'].'://'.$parser_url['host'];
            header(sprintf('Referer:%s',$u));
        }
        header("content-type:text/html; charset=utf-8");
        header(" Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36");;
        try{
            $meta_array = get_meta_tags( $url);
            foreach ($meta_array as &$item) {
                $item =iconv("GB2312","UTF-8",$item);
            }
            $this->encode_json(200,'获取成功',$meta_array);
        }catch (\Exception $e){
            $this->encode_json(200,'请手工录入关键字');
        }
    }


}
